package com.example.labSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.labSystem.entity.User;
import com.example.labSystem.mapper.UserMapper;
import com.example.labSystem.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 10
 * @since 2024-12-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    /**
     * 根据真实姓名获取用户列表，缓存查询结果
     *
     * @param fullName 真实姓名
     * @return 用户列表
     */
    @Override
    @Cacheable(value = "userCache", key = "#fullName", unless = "#result == null")
    public List<User> getUsersByFullName(String fullName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fullName", fullName);
        return this.list(queryWrapper);
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 用户信息
     */
    @Override
    @Cacheable(value = "userCache", key = "'login_' + #username", unless = "#result == null")
    public User login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username).eq("password", password);
        return this.getOne(queryWrapper);
    }

    /**
     * 检查用户是否为管理员
     *
     * @param userId 用户ID
     * @return 是否为管理员
     */
    @Override
    public boolean isAdmin(String userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userID", userId).eq("role", "admin");
        return this.count(queryWrapper) > 0;
    }

    /**
     * 检查用户名是否存在，缓存查询结果
     *
     * @param username 用户名
     * @return 是否存在
     */
    @Override
    @Cacheable(value = "usernameExistsCache", key = "#username")
    public boolean isUsernameExists(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return this.count(queryWrapper) > 0;
    }

    /**
     * 更新用户信息，并清除缓存
     *
     * @param user 用户信息
     * @return 更新成功标志
     */
    @Override
    @CachePut(value = "userCache", key = "#user.username")
    public boolean updateUser(User user) {
        return this.updateById(user);
    }

    /**
     * 删除用户信息，并清除缓存
     *
     * @param userId 用户ID
     * @return 删除成功标志
     */
    @Override
    @CacheEvict(value = "userCache", key = "#userId")
    public boolean deleteUser(String userId) {
        return this.removeById(userId);
    }
}
